import { Component } from 'react';

import { Group, Boxs, TextField,PhotoField,Button,ActionSheet,Toast,Dialog} from 'saltui';
const { HBox, Box } = Boxs;
const {
  IconButton,
  ButtonGroup,
} = Button;


import Options from './options';

let actionSheet1 ;
let actionSheet2 ;
export default class PageHome extends Component {
    /*handleChangePic(rows){
      this.setState({
        addques:rows,
      })
    }*/



    handleTextChange(name, newValue,no) {
        var rows = this.props.todo;
        rows[no][name] = newValue;
        this.props.onAdd(rows);
        this.setState({
          todos: rows,
        });
    // if (newValue.length > 5) {
    //   this.setState({
    //     errMsg: '最多输入5个字',
    //   });
    // } else {
    //   this.setState({
    //     errMsg: null,
    //   });
    // }
  }

  constructor(props) {
    super(props);
    var label = props.label;
    var todos = props.todo;
     this.state = {
        no:1,
        todos:todos,
        show:0
    };
    this.handleTextChange = this.handleTextChange.bind(this);

  }

  componentDidMount(){
    
    }


rnd(min, max){
  return min + Math.floor(Math.random() * (max - min + 1));
}
/*选择题型时生成排序码*/
setDataSort(){
  var date = new Date().getTime();
  // var min = 1000000000000000;
  // var max = 9999999999999999;
  // var list = this.props.todo;
  // var sort = list[list.length-1].dataSort;
  // var dataSort= "";
  // if(sort =='undefined' || sort == undefined || sort==''){
  //   dataSort = this.rnd(min, max);
  // }else{
  //   dataSort = this.rnd(Number(sort), max);
  // }
  return date;
}

 getInitialState () {
    return {
       t1: '',
      t2: 'aaaaaaaaaa',
      t3 : ["A"], 
    };
  }
  componentWillUnmount(){
    if(actionSheet1){
      actionSheet1.close();
    }
    if(actionSheet2){
      actionSheet2.close();
    }
  }
  handleAdd(e) {
    e.preventDefault();
    var Dom = ReactDOM.findDOMNode(this.refs.addnew);
    let t = this;
    var dataSort = this.setDataSort();
    actionSheet1 = ActionSheet.show({
            options: ['单选', '多选', '问答'],
            destructiveButtonIndex: -1,
            maskClosable: true,
          }, (index) => {
             var no = t.state.no ;
            no++;
            var newthing ;
            var type = '';
            if(index == '2'){//问答
              type = 'answer';
              newthing = {'topicSetting':{'willAnswer':'0','optionReNo':'0',"type":""},'dataSort':dataSort,
              'type':index+'','quesType':type+'','title':'问答题','titleInfo':'问答题','options':[{'content':''}]};
              t.setState({
                no:no
              });
              var rows = t.props.todo;
              rows.push(newthing);
              this.props.onAdd(rows);
            }else if(index == '0'){ //单选
               type = 'sinselect';
               newthing = {'topicSetting':{'willAnswer':'0','optionReNo':'0','ezQuABC':'1','optionArray':'1'},'dataSort':dataSort,
               'type':index+'','quesType':type+'','title':'单选题','titleInfo':'单选题','options':[{'optionsName':'A','optionsContent':'选项',
              'optionSetting':{"optionBlank":"0","optionBlankWill":"0","optionScore":"0",'optionImg':[]}}]};
                t.setState({
                  no:no
                });
                var rows = t.props.todo;
                rows.push(newthing);
              this.props.onAdd(rows);
            }else if(index == '1'){ //多选
              type = 'multiselect';
              newthing = {'topicSetting':{'willAnswer':'0','optionReNo':'0','ezQuABC':'1','optionArray':'1','minMultiselect':'1','maxMultiselect':'1'},'dataSort':dataSort,
                 'type':index+'','quesType':type+'','title':'多选题','titleInfo':'多选题','options':[{'optionsName':'A','optionsContent':'选项',
                 'optionSetting':{"optionBlank":"0","optionBlankWill":"0","optionScore":"0",'optionImg':[]}}]};
                t.setState({
                  no:no
                });
                var rows = t.props.todo;
                 rows.push(newthing);
              this.props.onAdd(rows);
            }
            
            
          });
      
  
   
    
  }

  setTodo(todos){
    this.setState({
      todos:todos
    })
  }

 handleChangeQues(e){
  var moveIndex=e.target.getAttribute('data-key');
  var length =  this.state.todos.length;
  var todoDel = this.props.todo;
  var propsDel = this.props;
  moveIndex = parseInt(moveIndex);
   actionSheet2 = ActionSheet.show({
            options: ['上移',  '下移', '删除'],
            destructiveButtonIndex: 2,
            maskClosable: true,
          }, (index) => {
          if(length>1){
            if(index=="2"){
              Dialog.confirm({
              title: '提示',
              content: '确认删除该题目',
              onConfirm() {
                  todoDel.splice(moveIndex,1);
                  propsDel.onDel(todoDel);
                  Toast.show({
                    type: 'success',
                    content: '删除成功',
                    onHide: function () {
                    }
                  });
                },
              onCancel() {
                  console.log('confirm cancel');
              }
              });
            }
            if(index=="0"){
              var rows= this.props.todo;
              if (moveIndex != 0) {
                let temp = rows[moveIndex - 1];
                rows[moveIndex- 1] = rows[moveIndex];
                rows[moveIndex] = temp;
                var value = rows[moveIndex- 1].dataSort;
                rows[moveIndex- 1].dataSort = rows[moveIndex].dataSort;
                rows[moveIndex].dataSort = value;
                this.setState({
                  todos:rows,
                },()=>{
                  var options1 = rows[moveIndex-1].options;
                  for(var i=0; i<options1.length; i++){
                    this.refs["OptionRef"+(moveIndex-1)].initUploadImgData("UploadImage"+(moveIndex-1)+""+i);
                  }
                  var options2 = rows[moveIndex].options;
                  for(var i=0; i<options2.length; i++){
                    this.refs["OptionRef"+(moveIndex)].initUploadImgData("UploadImage"+(moveIndex)+""+i);
                  }
                });
              }
            }
            if(index=="1"){
              var rows= this.props.todo;
              if (moveIndex != rows.length-1) {
                let temp = rows[moveIndex + 1];
                rows[moveIndex+ 1] = rows[moveIndex];
                rows[moveIndex] = temp;
                var value = rows[moveIndex].dataSort;
                rows[moveIndex].dataSort = rows[moveIndex+1].dataSort;
                rows[moveIndex+1].dataSort = value;
                this.setState({
                  todos:rows,
                },()=>{
                  var options1 = rows[moveIndex+1].options;
                  for(var i=0; i<options1.length; i++){
                    this.refs["OptionRef"+(moveIndex+1)].initUploadImgData("UploadImage"+(moveIndex+1)+""+i);
                  }
                  var options2 = rows[moveIndex].options;
                  for(var i=0; i<options2.length; i++){
                    this.refs["OptionRef"+(moveIndex)].initUploadImgData("UploadImage"+(moveIndex)+""+i);
                  }
                })
              }
            }
            }else{
              if(index=='2'){
                Toast.show({
              type: 'error',
              content: '至少保留一题',
              onHide: function () {}
          });
            return;
              }
            }
            
          });
  }




  //type2为问答
  handleChangePic(type,no,rows){
    var todos = this.state.todos;
    // if(type=='2'){
    //   todos[no]['content'] = rows
    //   this.setState({
    //     todos:todos,
    //   })
    // }else{
      todos[no]['options'] = rows;
      this.setState({
        todos:todos,
      })
   // }
    
  }

  render() {
     const t = this;
 ;
     
    return (
      <div>
        {
            this.state.todos.map(function(item,i){
              return (
       <div className="t-FAL-all">
          <Group.List >
            <TextField
              placeholder="请输入"
              label={<HBox className="t-FBJ"><Box>题型：{item.title}</Box><Box onClick={this.handleChangeQues.bind(this)} data-key={i} className="iconfont icon-more t-FCc t-rotate-90" ></Box></HBox>}
              layout="v"
              value={item.titleInfo}
              onChange={(value) => { t.handleTextChange('titleInfo', value,i); }}
            ></TextField>
            <Options
              ref={"OptionRef"+i}
              datakey={i}
              onAdd={this.handleChangePic.bind(this,item.type,i)}
              onDel={this.handleChangePic.bind(this,item.type,i)}
              options={item.options}
              type={item.type}
            />
          	
          </Group.List>                      
          </div>)}.bind(this))}
          <div onClick={this.handleAdd.bind(this)}  name="新增" ref="addnew">
             <div className="t-H44 t-LH44 t-FAC t-FCblue">添加题目</div>
            </div> 

            </div>
         
    )
}
}

